﻿using System;
using System.Linq;
using System.Collections.Specialized;
using EPiServer.PlugIn;
using EPiServer.Core;
using EPiServer;
using EPiServer.Filters;
using System.Text;

namespace Dropit.BlogPageProvider.PlugIn
{
	public class BlogPageProvider : EPiServer.PlugIn.PlugInAttribute
	{
		private static string PageProviderTemplateName = "DBPP{0}";

		public static void Start()
		{
			InitializePageProviders();
			EPiServer.DataFactory.Instance.PublishedPage += new EPiServer.PageEventHandler(Instance_PublishedPage);
		}

		private static void InitializePageProviders()
		{
			PropertyCriteriaCollection criterias = new PropertyCriteriaCollection();
			PropertyCriteria criteria = new PropertyCriteria();

			criteria.Name = "PageTypeID";
			criteria.Type = PropertyDataType.PageType;
			criteria.Condition = CompareCondition.Equal;
			criteria.Value = Settings.BlogSettingsPageTypeId.ToString();
			criterias.Add(criteria);
			foreach (PageData page in EPiServer.DataFactory.Instance.FindPagesWithCriteria(PageReference.RootPage, criterias))
			{
				if (page.Property["DisconnectPageProvider"] == null || page.Property["DisconnectPageProvider"].IsNull)
				{
					SetupPageProvider(page);
				}
			}
		}

		private static void SetupPageProvider(PageData page)
		{
			RemovePageProvider(page);
			string providerName = string.Format(PageProviderTemplateName, page.PageLink.ID);
			PageStore pageStore = new PageStore();
			NameValueCollection valueCol = new NameValueCollection();
			valueCol.Add("entryPoint", page.PageLink.ID.ToString());
			valueCol.Add("capabilities", "Create, Edit, Delete");
			pageStore.Initialize(providerName, valueCol);
			EPiServer.DataFactory.Instance.ProviderMap.AddPageProvider(pageStore);
		}

		private static void RemovePageProvider(PageData page)
		{
			string providerName = string.Format(PageProviderTemplateName, page.PageLink.ID);
			if (EPiServer.DataFactory.Instance.ProviderMap.GetPageProvider(providerName) != null)
			{
				EPiServer.DataFactory.Instance.ProviderMap.RemovePageProvider(providerName);
			}
		}

		private static void Instance_PublishedPage(object sender, EPiServer.PageEventArgs e)
		{
			if (e.Page != null && e.Page.PageTypeID == Settings.BlogSettingsPageTypeId)
			{
				if (e.Page.Property["DisconnectPageProvider"] == null || e.Page.Property["DisconnectPageProvider"].IsNull)
				{
					SetupPageProvider(e.Page);
				}
				else
				{
					RemovePageProvider(e.Page);
				}
			}
		}
	}
}